package com.springapp.mvc.newspsi.service;

import com.springapp.mvc.newspsi.model.Comment;
import com.springapp.mvc.newspsi.repositories.CommentRepositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * User: Станислав
 * Date: 15.09.14
 */
@Service
public class CommentService {
    @Autowired
    private CommentRepositories commentRepositories;


    public CommentService() {
    }

    public void saveComment(Comment comment) {
        commentRepositories.save(comment);
    }

    public void deleteComment(Comment comment) {
        commentRepositories.delete(comment);
    }

    public Iterable<Comment> getAllComment() {
        return commentRepositories.findAll();
    }

    public List<Comment> findById(Integer id) {
        List<Comment> comments = new ArrayList<Comment>();
        Iterator<Comment> iterator = getAllComment().iterator();
        Comment tmp;
        while (iterator.hasNext()) {
            tmp = iterator.next();
            if (tmp.getId_comment() == id) {
                comments.add(tmp);
            }
        }
        return comments;
    }

    public List<Comment> findByTextComment(CharSequence text) {
        List<Comment> comments = new ArrayList<Comment>();
        Iterator<Comment> iterator = getAllComment().iterator();
        Comment tmp;
        while (iterator.hasNext()) {
            tmp = iterator.next();
            if (tmp.getText_comment().contains(text)) {
                comments.add(tmp);
            }
        }
        return comments;
    }

    public List<Comment> findByAuthor(String author) {
        List<Comment> comments = new ArrayList<Comment>();
        Iterator<Comment> iterator = getAllComment().iterator();
        Comment tmp;
        while (iterator.hasNext()) {
            tmp = iterator.next();
            if (tmp.getAuthor().equalsIgnoreCase(author)) {
                comments.add(tmp);
            }
        }
        return comments;
    }
}
